package com.farm.intercepter;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.farm.common.BaseContext;
import com.farm.util.AppJwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

// 登录校验器
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map = new HashMap<>();

        try {
            if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
                System.out.println("OPTIONS请求，放行");
                return true;
            }
            log.info("这里是token:");
            String token = request.getHeader("token");
            System.out.println(token);
            Claims body = AppJwtUtil.getJws(token).getBody();
            log.info(token);
            AppJwtUtil.verifyToken(body);//验证令牌
            String  openid = (body.get("openId")).toString();
            BaseContext.setCurrentOpenId(openid);
            return true;
        }catch (Exception e){
            log.info("非小程序");
        }

        //获取请求头中的令牌
        try {
            if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
                System.out.println("OPTIONS请求，放行");
                return true;
            }
            log.info("这里是token:");
            String token = request.getHeader("token");
            Claims body = AppJwtUtil.getJws(token).getBody();
            Long id = Long.valueOf(((Long)body.get("id")).toString());
            BaseContext.setCurrentId(id);

            log.info(token);
            AppJwtUtil.verifyToken(body);//验证令牌
            return true;
        }catch (IllegalArgumentException e){
            System.out.println("没有token！");
            //e.printStackTrace();
            map.put("msg", "没有token！");
        }
        catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg", "无效签名！");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg", "token过期！");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg", "token算法不一致！");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "token无效！");
        }
        map.put("state", false);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        // 返回false请求直接接收，不会进入Controller
        return false;
    }
}